/*
 * Powered By 
 * Since 2010 - 2016
 */

package com.rf.sys.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;	

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.rf.sys.bean.UserBean;
import com.rf.sys.dao.UserMapper;
import com.rf.sys.dao.SqlAdapterMapper;
import com.rf.sys.dao.UserRoleMapper;
import com.rf.sys.model.User;
import com.rf.sys.model.UserExample;
import com.rf.sys.model.UserRole;
import com.rf.sys.model.UserRoleExample;
import com.rf.sys.service.UserService;
import com.rf.sys.utils.ConfigUtils;
import com.rf.sys.utils.PageUtils;
import com.rf.sys.utils.UuidUtil;

@Service("userService")
public class UserServiceImpl implements UserService {
	
	@Autowired
   	private SqlAdapterMapper sqlAdapterMapper;//注入dao
   	@Autowired
   	private UserMapper userMapper;//注入dao
   	@Autowired
   	private UserRoleMapper userRoleMapper;//注入dao

   	/**
	 * 根据id获取数据
	 * @param userId
	 * @return User
	 */
   	@Override
	public User getUserByID(String id) throws Exception{
		// TODO Auto-generated method stub
		return userMapper.selectByPrimaryKey(id);
	}
	
	/**
	 * 根据User获取数据
	 * @param User
	 * @return List<User>
	 */
	@Override
	public List<User> getUser(User user) throws Exception{
		// TODO Auto-generated method stub
		UserExample example = new UserExample();
		com.rf.sys.model.UserExample.Criteria criteria= example.createCriteria();
		if(user.getAccountName() != null && !user.getAccountName().equals("")){
			criteria.andAccountNameEqualTo(user.getAccountName());
		}
		List<User> list = userMapper.selectByExample(example);
		return list;
	}
	
	/**
	 * 根据User获取数据用于验证账号是否重复
	 * @param User
	 * @return List<User>
	 */
	@Override
	public List<User> getUserRepeat(User user) throws Exception{
		// TODO Auto-generated method stub
		UserExample example = new UserExample();
		com.rf.sys.model.UserExample.Criteria criteria= example.createCriteria();
		if(user.getAccountName() != null && !user.getAccountName().equals("")){
			criteria.andAccountNameEqualTo(user.getAccountName());
		}
		if(user.getId() != null){
			criteria.andIdNotEqualTo(user.getId());
		}
		criteria.andStateNotEqualTo(ConfigUtils.USERDELSTATE);
		List<User> list = userMapper.selectByExample(example);
		return list;
	}
	
	/**
	 * 获取所有数据
	 * @param 
	 * @return List<User>
	 */
	@Override
	public List<User> getUser() throws Exception{
		// TODO Auto-generated method stub
		UserExample example = new UserExample();
		return userMapper.selectByExample(example);
	}
	
	/**
	 * 获取用户是否有管理员角色
	 * @param userId 用户ID
	 * @return true 是  false 不是
	 */
	@Override
	public boolean getUserIsAdmin(String userId) throws Exception{
		// TODO Auto-generated method stub
		String sql = "select r.role_key from sys_user u,sys_user_role ur,sys_role r where "
				+ " u.id = ur.user_id and ur.role_id = r.id and r.state = '100101' and u.id = '"+userId+"'";
		List<Map<String, Object>> list = sqlAdapterMapper.selectSQL(sql);
		for(Map mpa:list){
			String roleKey = (String) mpa.get("ROLE_KEY");
			if("admin".equals(roleKey)){
				return true;
			}
		}
		return false;
	}
   	
	/**
	 * 保存信息
	 * @param User
	 * @return
	 */
	@Override
	public void addUser(User user) throws Exception{
		// TODO Auto-generated method stub
		user.setId(UuidUtil.get32UUID());
		userMapper.insert(user);
	}

	/**
	 * 修改数据
	 * @param User
	 * @param
	 */
	@Override
	public void updateUser(User user) throws Exception{
		// TODO Auto-generated method stub
		userMapper.updateByPrimaryKeySelective(user);
	}
	
	/**
	 * 删除数据
	 * @param userId
	 * @param
	 */
	@Override
	public void deleteUser(String id) throws Exception{
		// TODO Auto-generated method stub
		userMapper.deleteByPrimaryKey(id);
	}
	
	/**
	 * 删除数据
	 * @param userId
	 * @param
	 */
	@Override
	public void deleteUserState(String ids) throws Exception{
		// TODO Auto-generated method stub
		String sql = "update sys_user set state = "+ConfigUtils.USERDELSTATE +" where id in("+ids+")";
		sqlAdapterMapper.updateSQL(sql);
	}
	
	/**
	 * 分配角色
	 * @param userId
	 * @param roleid
	 * @param
	 */
	@Override
	public void allot(String userid,String roleid) throws Exception{
		//删除该用户所分配的角色
		String sql = "delete from sys_user_role where user_id = '"+userid+"'";
		sqlAdapterMapper.deleteSQL(sql);
		String[] rids = roleid.split(",");
		for(int i=0;i<rids.length;i++){
			UserRole record = new UserRole();
			record.setId(UuidUtil.get32UUID());
			record.setUserId(userid);
			record.setRoleId(rids[i]);
			userRoleMapper.insert(record);
		}
		
	}

	/**
	 * 获取数据分页
	 * @param User 
	 * @param limit
	 * @param offset
	 * @return Map
	 */
	@Override
	public Map getUserPage(User user, PageUtils pageUtils) throws Exception{
		UserExample example = new UserExample();
		com.rf.sys.model.UserExample.Criteria criteria= example.createCriteria();
		if(user.getAccountName()!=null && !user.getAccountName().equals("")){
			criteria.andAccountNameLike("%"+user.getAccountName()+"%");
		}
		if(user.getUserName()!=null && !user.getUserName().equals("")){
			criteria.andUserNameLike("%"+user.getUserName()+"%");
		}
		if(user.getState()!=null && !user.getState().equals("")){
			criteria.andStateEqualTo(user.getState());
		}
		criteria.andStateNotEqualTo(ConfigUtils.USERDELSTATE);//用户状态不等于删除
		example.setOrderByClause(" create_time desc ");
		//获取第offset页，每页共limit条内容，默认查询总数count
		Page p = PageHelper.startPage(pageUtils.getPage(), pageUtils.getRows());
		//下一条执行语句，即为要被转换的语句
		List<User> list = userMapper.selectByExample(example);
		List<UserRole>  urList = userRoleMapper.selectByExample(null);
		List<UserBean> ubList = new ArrayList<UserBean>();
		for(User u : list){
			UserBean ub = new UserBean();
			ub.setAccountName(u.getAccountName());
			ub.setCreateTime(u.getCreateTime());
			ub.setCredentialsSalt(u.getCredentialsSalt());
			ub.setDescription(u.getDescription());
			ub.setId(u.getId());
			ub.setPassword(u.getPassword());
			ub.setState(u.getState());
			ub.setUserName(u.getUserName());
			String role = "";
			for(UserRole ur : urList){
				//判断该条用户角色信息是否是当前用户的信息
				if(ur.getUserId().equals(u.getId())){
					role+=ur.getRoleId()+",";
				}
			}
			if(!role.equals("")){
				ub.setRole(role.substring(0, (role.length()-1)));
			}
			ubList.add(ub);
		}
		Map dateMap = new HashMap();
	    dateMap.put("total", p.getTotal());
	    dateMap.put("rows", ubList);
		return dateMap;
	}
}

